<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta name="description" content="最近邻检索和创建数据库"/>

    <meta name="twitter:card" content="summary"/>
    <meta name="twitter:image:src" content="https://avatars1.githubusercontent.com/u/64068543?s=400&amp;v=4"/>
    <meta name="twitter:title" content="最近邻检索的数据库"/>
    <meta name="twitter:description" content="最近邻检索和创建数据库"/>
    <meta name="twitter:site" content="@labmlai"/>
    <meta name="twitter:creator" content="@labmlai"/>

    <meta property="og:url" content="https://nn.labml.ai/transformers/retro/database.html"/>
    <meta property="og:title" content="最近邻检索的数据库"/>
    <meta property="og:image" content="https://avatars1.githubusercontent.com/u/64068543?s=400&amp;v=4"/>
    <meta property="og:site_name" content="最近邻检索的数据库"/>
    <meta property="og:type" content="object"/>
    <meta property="og:title" content="最近邻检索的数据库"/>
    <meta property="og:description" content="最近邻检索和创建数据库"/>

    <title>最近邻检索的数据库</title>
    <link rel="shortcut icon" href="/icon.png"/>
    <link rel="stylesheet" href="../../pylit.css?v=1">
    <link rel="canonical" href="https://nn.labml.ai/transformers/retro/database.html"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.13.18/dist/katex.min.css" integrity="sha384-zTROYFVGOfTw7JV7KUu8udsvW2fx4lWOsCEDqhBreBwlHI4ioVRtmIvEThzJHGET" crossorigin="anonymous">

    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-4V3HC8HBLH"></script>
    <script>
        window.dataLayer = window.dataLayer || [];

        function gtag() {
            dataLayer.push(arguments);
        }

        gtag('js', new Date());

        gtag('config', 'G-4V3HC8HBLH');
    </script>
</head>
<body>
<div id='container'>
    <div id="background"></div>
    <div class='section'>
        <div class='docs'>
            <p>
                <a class="parent" href="/">home</a>
                <a class="parent" href="../index.html">transformers</a>
                <a class="parent" href="index.html">retro</a>
            </p>
            <p>
                <a href="https://github.com/labmlai/annotated_deep_learning_paper_implementations" target="_blank">
                    <img alt="Github"
                         src="https://img.shields.io/github/stars/labmlai/annotated_deep_learning_paper_implementations?style=social"
                         style="max-width:100%;"/></a>
                <a href="https://twitter.com/labmlai" rel="nofollow" target="_blank">
                    <img alt="Twitter"
                         src="https://img.shields.io/twitter/follow/labmlai?style=social"
                         style="max-width:100%;"/></a>
            </p>
            <p>
                <a href="https://github.com/labmlai/annotated_deep_learning_paper_implementations/tree/master/labml_nn/transformers/retro/database.py" target="_blank">
                    View code on Github</a>
            </p>
        </div>
    </div>
    <div class='section' id='section-0'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-0'>#</a>
            </div>
            <h1>最近邻检索的数据库</h1>
<p>这是构建数据库并检索 RETRO <a href="index.html">模型的最近邻域</a>。</p>
</a><p>我们使用 <a href="https://faiss.ai/">FAISS 库作为数据库，而论文使用了 ScanN 库。</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">16</span><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span><span class="p">,</span> <span class="n">Optional</span>
<span class="lineno">17</span>
<span class="lineno">18</span><span class="kn">import</span> <span class="nn">faiss</span>
<span class="lineno">19</span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="lineno">20</span><span class="kn">import</span> <span class="nn">torch</span>
<span class="lineno">21</span>
<span class="lineno">22</span><span class="kn">from</span> <span class="nn">labml</span> <span class="kn">import</span> <span class="n">lab</span><span class="p">,</span> <span class="n">monit</span>
<span class="lineno">23</span><span class="kn">from</span> <span class="nn">labml_helpers.datasets.text</span> <span class="kn">import</span> <span class="n">TextFileDataset</span>
<span class="lineno">24</span><span class="kn">from</span> <span class="nn">labml_nn.transformers.retro.bert_embeddings</span> <span class="kn">import</span> <span class="n">BERTChunkEmbeddings</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-1'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-1'>#</a>
            </div>
            <h2>建立数据库</h2>
<ul><li><code  class="highlight"><span></span><span class="n">chunk_len</span></code>
是块的长度（字符数）</li>
<li><code  class="highlight"><span></span><span class="n">batch_size</span></code>
是计算时要使用的批次大小<span ><span class="katex"><span aria-hidden="true" class="katex-html"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord coloredeq eqa" style=""><span class="mord text" style=""><span class="mord" style="">B</span><span class="mord sizing reset-size6 size5" style=""><span class="mord" style="">ERT</span></span></span><span class="mopen" style="">(</span><span class="mord mathnormal" style="margin-right:0.10903em">N</span><span class="mclose" style="">)</span></span></span></span></span></span></li>
<li><code  class="highlight"><span></span><span class="n">d_emb</span></code>
是要在 <a href="https://faiss.ai/cpp_api/struct/structfaiss_1_1IndexIVFPQ.html">FAISS 索引中选择的<span ><span class="katex"><span aria-hidden="true" class="katex-html"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord coloredeq eqa" style=""><span class="mord text" style=""><span class="mord" style="">B</span><span class="mord sizing reset-size6 size5" style=""><span class="mord" style="">ERT</span></span></span><span class="mopen" style="">(</span><span class="mord mathnormal" style="margin-right:0.10903em">N</span><span class="mclose" style="">)</span></span></span></span></span></span>嵌入列表中要</a>素的数量</li>
<li><code  class="highlight"><span></span><span class="n">n_centeroids</span></code>
是索引中的列表数</li>
<li><code  class="highlight"><span></span><span class="n">code_size</span></code>
索引中的编码向量大小</li>
<li><code  class="highlight"><span></span><span class="n">n_probe</span></code>
是要探测的列表的数量</li>
<li>`n_train'是用于训练索引的键的数量</li></ul>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">27</span><span class="k">def</span> <span class="nf">build_database</span><span class="p">(</span><span class="n">chunk_len</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">16</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">64</span><span class="p">,</span> <span class="n">d_emb</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">768</span><span class="p">,</span> <span class="n">n_centeroids</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">256</span><span class="p">,</span>
<span class="lineno">28</span>                   <span class="n">code_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">64</span><span class="p">,</span> <span class="n">n_probe</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">8</span><span class="p">,</span> <span class="n">n_train</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">50_000</span><span class="p">):</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-2'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-2'>#</a>
            </div>
            <p>加载数据集文本文件</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">43</span>    <span class="n">dataset</span> <span class="o">=</span> <span class="n">TextFileDataset</span><span class="p">(</span>
<span class="lineno">44</span>        <span class="n">lab</span><span class="o">.</span><span class="n">get_data_path</span><span class="p">()</span> <span class="o">/</span> <span class="s1">&#39;tiny_shakespeare.txt&#39;</span><span class="p">,</span>
<span class="lineno">45</span>        <span class="nb">list</span><span class="p">,</span>
<span class="lineno">46</span>        <span class="n">url</span><span class="o">=</span><span class="s1">&#39;https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt&#39;</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-3'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-3'>#</a>
            </div>
            <p>获取训练数据（字符串）</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">49</span>    <span class="n">text</span> <span class="o">=</span> <span class="n">dataset</span><span class="o">.</span><span class="n">train</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-4'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-4'>#</a>
            </div>
            <p>将文本分成大块<code  class="highlight"><span></span><span class="n">chunk_length</span></code>
</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">52</span>    <span class="n">chunks</span> <span class="o">=</span> <span class="p">[</span><span class="n">text</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span> <span class="o">+</span> <span class="n">chunk_len</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">text</span><span class="p">),</span> <span class="n">chunk_len</span><span class="p">)</span> <span class="k">if</span> <span class="n">i</span> <span class="o">+</span> <span class="n">chunk_len</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">&lt;</span> <span class="nb">len</span><span class="p">(</span><span class="n">text</span><span class="p">)]</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-5'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-5'>#</a>
            </div>
            <p>获取每个区块的偏移量</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">54</span>    <span class="n">chunk_offsets</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">text</span><span class="p">),</span> <span class="n">chunk_len</span><span class="p">)</span> <span class="k">if</span> <span class="n">i</span> <span class="o">+</span> <span class="n">chunk_len</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">&lt;</span> <span class="nb">len</span><span class="p">(</span><span class="n">text</span><span class="p">)])</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-6'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-6'>#</a>
            </div>
            <p>区块数</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">56</span>    <span class="n">n_chunks</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunks</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-7'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-7'>#</a>
            </div>
            <p>初始化 BERT 以获取<span ><span class="katex"><span aria-hidden="true" class="katex-html"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord coloredeq eqa" style=""><span class="mord text" style=""><span class="mord" style="">B</span><span class="mord sizing reset-size6 size5" style=""><span class="mord" style="">ERT</span></span></span><span class="mopen" style="">(</span><span class="mord mathnormal" style="margin-right:0.10903em">N</span><span class="mclose" style="">)</span></span></span></span></span></span></p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">59</span>    <span class="n">bert</span> <span class="o">=</span> <span class="n">BERTChunkEmbeddings</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">device</span><span class="p">(</span><span class="s1">&#39;cuda:0&#39;</span><span class="p">))</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-8'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-8'>#</a>
            </div>
            <p>通过处理每次迭代的块<code  class="highlight"><span></span><span class="n">batch_size</span></code>
数来获取区块嵌入</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">62</span>    <span class="n">chunk_emb</span> <span class="o">=</span> <span class="p">[]</span>
<span class="lineno">63</span>    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">monit</span><span class="o">.</span><span class="n">iterate</span><span class="p">(</span><span class="s1">&#39;Get embeddings&#39;</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">n_chunks</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">)):</span>
<span class="lineno">64</span>        <span class="n">chunk_emb</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">bert</span><span class="p">(</span><span class="n">chunks</span><span class="p">[</span><span class="n">i</span><span class="p">:</span> <span class="n">i</span> <span class="o">+</span> <span class="n">batch_size</span><span class="p">])</span><span class="o">.</span><span class="n">cpu</span><span class="p">())</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-9'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-9'>#</a>
            </div>
            <p>将它们合并成单个张量</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">66</span>    <span class="n">chunk_emb</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">cat</span><span class="p">(</span><span class="n">chunk_emb</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">numpy</span><span class="p">()</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-10'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-10'>#</a>
            </div>
            <p>创建 <a href="https://faiss.ai/cpp_api/struct/structfaiss_1_1IndexIVFPQ.html">FAISS 指数</a></p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">69</span>    <span class="n">quantizer</span> <span class="o">=</span> <span class="n">faiss</span><span class="o">.</span><span class="n">IndexFlatL2</span><span class="p">(</span><span class="n">d_emb</span><span class="p">)</span>
<span class="lineno">70</span>    <span class="n">index</span> <span class="o">=</span> <span class="n">faiss</span><span class="o">.</span><span class="n">IndexIVFPQ</span><span class="p">(</span><span class="n">quantizer</span><span class="p">,</span> <span class="n">d_emb</span><span class="p">,</span> <span class="n">n_centeroids</span><span class="p">,</span> <span class="n">code_size</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span>
<span class="lineno">71</span>    <span class="n">index</span><span class="o">.</span><span class="n">nprobe</span> <span class="o">=</span> <span class="n">n_probe</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-11'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-11'>#</a>
            </div>
            <p>获取区块索引的随机样本</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">74</span>    <span class="n">random_sample</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="n">n_chunks</span><span class="p">),</span> <span class="n">size</span><span class="o">=</span><span class="p">[</span><span class="nb">min</span><span class="p">(</span><span class="n">n_train</span><span class="p">,</span> <span class="n">n_chunks</span><span class="p">)],</span> <span class="n">replace</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-12'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-12'>#</a>
            </div>
            <p>训练索引以存储密钥</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">77</span>    <span class="k">with</span> <span class="n">monit</span><span class="o">.</span><span class="n">section</span><span class="p">(</span><span class="s1">&#39;Train index&#39;</span><span class="p">):</span>
<span class="lineno">78</span>        <span class="n">index</span><span class="o">.</span><span class="n">train</span><span class="p">(</span><span class="n">chunk_emb</span><span class="p">[</span><span class="n">random_sample</span><span class="p">])</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-13'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-13'>#</a>
            </div>
            <p>将块按大小批次添加到索引中<code  class="highlight"><span></span><span class="mi">1024</span></code>
</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">81</span>    <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">monit</span><span class="o">.</span><span class="n">iterate</span><span class="p">(</span><span class="s1">&#39;Index&#39;</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">n_chunks</span><span class="p">,</span> <span class="mi">1024</span><span class="p">)):</span>
<span class="lineno">82</span>        <span class="n">e</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">s</span> <span class="o">+</span> <span class="mi">1024</span><span class="p">,</span> <span class="n">n_chunks</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-14'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-14'>#</a>
            </div>
            <p>添加到索引</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">84</span>        <span class="n">index</span><span class="o">.</span><span class="n">add_with_ids</span><span class="p">(</span><span class="n">chunk_emb</span><span class="p">[</span><span class="n">s</span><span class="p">:</span><span class="n">e</span><span class="p">],</span> <span class="n">chunk_offsets</span><span class="p">[</span><span class="n">s</span><span class="p">:</span> <span class="n">e</span><span class="p">])</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-15'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-15'>#</a>
            </div>
            <p>保存索引</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">87</span>    <span class="k">with</span> <span class="n">monit</span><span class="o">.</span><span class="n">section</span><span class="p">(</span><span class="s1">&#39;Save&#39;</span><span class="p">):</span>
<span class="lineno">88</span>        <span class="n">faiss</span><span class="o">.</span><span class="n">write_index</span><span class="p">(</span><span class="n">index</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">lab</span><span class="o">.</span><span class="n">get_data_path</span><span class="p">()</span> <span class="o">/</span> <span class="s1">&#39;retro.index&#39;</span><span class="p">))</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-16'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-16'>#</a>
            </div>
            <h2>检索最近邻居的索引</h2>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">91</span><span class="k">class</span> <span class="nc">RetroIndex</span><span class="p">:</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-17'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-17'>#</a>
            </div>
            <ul><li><code  class="highlight"><span></span><span class="n">chunk_len</span></code>
是区块长度</li>
<li><code  class="highlight"><span></span><span class="n">n_probe</span></code>
是要探测的列表的数量</li>
<li><code  class="highlight"><span></span><span class="n">n_neighbors</span></code>
是要检索的邻居数量</li>
<li><code  class="highlight"><span></span><span class="n">n_extra</span></code>
是要检索的额外邻居的数量，因为我们将移除与查询块重叠的邻居</li>
<li><code  class="highlight"><span></span><span class="n">exclude_neighbor_span</span></code>
是检查重叠时要避免的额外文本长度</li></ul>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">96</span>    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">chunk_len</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">16</span><span class="p">,</span> <span class="n">n_probe</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">8</span><span class="p">,</span>
<span class="lineno">97</span>                 <span class="n">n_neighbors</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">2</span><span class="p">,</span> <span class="n">n_extra</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">2</span><span class="p">,</span>
<span class="lineno">98</span>                 <span class="n">exclude_neighbor_span</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">8</span><span class="p">):</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-18'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-18'>#</a>
            </div>
            
        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">108</span>        <span class="bp">self</span><span class="o">.</span><span class="n">n_neighbors</span> <span class="o">=</span> <span class="n">n_neighbors</span>
<span class="lineno">109</span>        <span class="bp">self</span><span class="o">.</span><span class="n">chunk_len</span> <span class="o">=</span> <span class="n">chunk_len</span>
<span class="lineno">110</span>        <span class="bp">self</span><span class="o">.</span><span class="n">exclude_neighbor_span</span> <span class="o">=</span> <span class="n">exclude_neighbor_span</span>
<span class="lineno">111</span>        <span class="bp">self</span><span class="o">.</span><span class="n">n_extra</span> <span class="o">=</span> <span class="n">n_extra</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-19'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-19'>#</a>
            </div>
            <p>初始化 BERT 以获取<span ><span class="katex"><span aria-hidden="true" class="katex-html"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord coloredeq eqa" style=""><span class="mord text" style=""><span class="mord" style="">B</span><span class="mord sizing reset-size6 size5" style=""><span class="mord" style="">ERT</span></span></span><span class="mopen" style="">(</span><span class="mord mathnormal" style="margin-right:0.10903em">N</span><span class="mclose" style="">)</span></span></span></span></span></span></p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">114</span>        <span class="bp">self</span><span class="o">.</span><span class="n">bert</span> <span class="o">=</span> <span class="n">BERTChunkEmbeddings</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">device</span><span class="p">(</span><span class="s1">&#39;cuda:0&#39;</span><span class="p">))</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-20'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-20'>#</a>
            </div>
            <p>装载数据库</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">116</span>        <span class="k">with</span> <span class="n">monit</span><span class="o">.</span><span class="n">section</span><span class="p">(</span><span class="s1">&#39;Load index&#39;</span><span class="p">):</span>
<span class="lineno">117</span>            <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">=</span> <span class="n">faiss</span><span class="o">.</span><span class="n">read_index</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">lab</span><span class="o">.</span><span class="n">get_data_path</span><span class="p">()</span> <span class="o">/</span> <span class="s1">&#39;retro.index&#39;</span><span class="p">))</span>
<span class="lineno">118</span>            <span class="bp">self</span><span class="o">.</span><span class="n">index</span><span class="o">.</span><span class="n">nprobe</span> <span class="o">=</span> <span class="n">n_probe</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-21'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-21'>#</a>
            </div>
            <h4>筛选与查询重叠的邻域</h4>
<p>邻居的位置由给出<code  class="highlight"><span></span><span class="n">neighbor_offsets</span></code>
，查询块的位置为<code  class="highlight"><span></span><span class="n">offset</span></code>
。</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">120</span>    <span class="k">def</span> <span class="nf">filter_neighbors</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">offset</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">neighbor_offsets</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">]):</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-22'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-22'>#</a>
            </div>
            
        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">127</span>        <span class="k">return</span> <span class="p">[</span><span class="n">n</span> <span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="n">neighbor_offsets</span>
<span class="lineno">128</span>                <span class="k">if</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="n">offset</span> <span class="o">-</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">chunk_len</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">exclude_neighbor_span</span><span class="p">)</span>
<span class="lineno">129</span>                <span class="ow">or</span> <span class="n">n</span> <span class="o">&gt;</span> <span class="n">offset</span> <span class="o">+</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">chunk_len</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">exclude_neighbor_span</span><span class="p">)]</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-23'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-23'>#</a>
            </div>
            <h3>检索最近的邻居</h3>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">131</span>    <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">query_chunks</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">],</span> <span class="n">offsets</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">]]):</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-24'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-24'>#</a>
            </div>
            <p>获取<span ><span class="katex"><span aria-hidden="true" class="katex-html"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord coloredeq eqa" style=""><span class="mord text" style=""><span class="mord" style="">B</span><span class="mord sizing reset-size6 size5" style=""><span class="mord" style="">ERT</span></span></span><span class="mopen" style="">(</span><span class="mord mathnormal" style="margin-right:0.10903em">N</span><span class="mclose" style="">)</span></span></span></span></span></span>查询区块</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">137</span>        <span class="n">emb</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">bert</span><span class="p">(</span><span class="n">query_chunks</span><span class="p">)</span><span class="o">.</span><span class="n">cpu</span><span class="p">()</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-25'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-25'>#</a>
            </div>
            <p>从数据库中获取<code  class="highlight"><span></span><span class="n">n_neighbors</span> <span class="o">+</span> <span class="n">n_extra</span></code>
最近的邻居</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">140</span>        <span class="n">distance</span><span class="p">,</span> <span class="n">neighbor_offsets</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">index</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">emb</span><span class="o">.</span><span class="n">numpy</span><span class="p">(),</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_neighbors</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_extra</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-26'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-26'>#</a>
            </div>
            <p>如果给出了查询区块偏移量，请过滤掉重叠的块</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">143</span>        <span class="k">if</span> <span class="n">offsets</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="lineno">144</span>            <span class="n">neighbor_offsets</span> <span class="o">=</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">filter_neighbors</span><span class="p">(</span><span class="n">off</span><span class="p">,</span> <span class="n">n_off</span><span class="p">)</span>
<span class="lineno">145</span>                                <span class="k">for</span> <span class="n">off</span><span class="p">,</span> <span class="n">n_off</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">offsets</span><span class="p">,</span> <span class="n">neighbor_offsets</span><span class="p">)]</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-27'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-27'>#</a>
            </div>
            <p>筛选<code  class="highlight"><span></span><span class="n">n_neighbors</span></code>
后获取最接近的值</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">148</span>        <span class="n">neighbor_offsets</span> <span class="o">=</span> <span class="p">[</span><span class="n">n_off</span><span class="p">[:</span><span class="bp">self</span><span class="o">.</span><span class="n">n_neighbors</span><span class="p">]</span> <span class="k">for</span> <span class="n">n_off</span> <span class="ow">in</span> <span class="n">neighbor_offsets</span><span class="p">]</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-28'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-28'>#</a>
            </div>
            <p></p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">151</span>        <span class="k">return</span> <span class="n">neighbor_offsets</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-29'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-29'>#</a>
            </div>
            <p></p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">155</span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
<span class="lineno">156</span>    <span class="n">build_database</span><span class="p">()</span></pre></div>
        </div>
    </div>
    <div class='footer'>
        <a href="https://labml.ai">labml.ai</a>
    </div>
</div>
<script src=../../interactive.js?v=1"></script>
<script>
    function handleImages() {
        var images = document.querySelectorAll('p>img')

        for (var i = 0; i < images.length; ++i) {
            handleImage(images[i])
        }
    }

    function handleImage(img) {
        img.parentElement.style.textAlign = 'center'

        var modal = document.createElement('div')
        modal.id = 'modal'

        var modalContent = document.createElement('div')
        modal.appendChild(modalContent)

        var modalImage = document.createElement('img')
        modalContent.appendChild(modalImage)

        var span = document.createElement('span')
        span.classList.add('close')
        span.textContent = 'x'
        modal.appendChild(span)

        img.onclick = function () {
            console.log('clicked')
            document.body.appendChild(modal)
            modalImage.src = img.src
        }

        span.onclick = function () {
            document.body.removeChild(modal)
        }
    }

    handleImages()
</script>
</body>
</html>